<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div class="search" v-show="showSearch">
        <el-form :model="queryParams" ref="queryFormRef" :inline="true" label-width="68px" class="search-form">
          <el-form-item label="关键字" prop="keyword">
            <el-input v-model="queryParams.keyword" placeholder="请输入姓名或学号" clearable style="width: 240px" @keyup.enter="handleQuery" />
          </el-form-item>
          <el-form-item label="所属班级" prop="classId">
            <ClassTree v-model="queryParams.classId" gradeDisabled />
          </el-form-item>
          <el-form-item label="人员类型" prop="accommodationType">
            <el-select v-model="queryParams.accommodationType" placeholder="请选择住宿类型" clearable>
              <el-option v-for="dict in student_accommodation_type" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="Plus" @click="handleAdd" v-hasPermi="['office:student:add']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button icon="Edit" :disabled="single" @click="handleUpdate()" v-hasPermi="['office:student:edit']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['office:student:remove']">删除</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button icon="Download" @click="handleExport" v-hasPermi="['office:student:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <el-table
        v-loading="loading"
        :data="studentList"
        @selection-change="handleSelectionChange"
        @row-dblclick="(row: any, column: any, event: Event) => handleUpdate(row)"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="姓名" align="center" prop="realName" />
        <el-table-column label="人员类型" align="center" prop="accommodationType">
          <template #default="scope">
            <dict-tag :options="student_accommodation_type" :value="scope.row.accommodationType" />
          </template>
        </el-table-column>
        <el-table-column label="所属班级/部门" align="center" prop="className" />
        <el-table-column label="人员分组" align="center" prop="strategyGroupNames" />
        <el-table-column label="通行规则" align="center" prop="strategyNames" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="修改" placement="top">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['office:student:edit']"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['office:student:remove']"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
  </div>
</template>

<script setup name="Student" lang="ts">
import { pageStudent, getStudent, delStudent, addStudent, updateStudent } from '@/api/office/student';
import { StudentVO, StudentQuery, StudentForm } from '@/api/office/student/types';
import { listClassInfo, classTree } from '@/api/office/class';
import { listGradeInfo } from '@/api/office/grade';
import { uuid } from '@/utils/ruoyi';
const props = defineProps({
  parentId: String || Number || undefined,
  groupId: String || Number || undefined,
  groupType: String || Number || undefined
});
const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { student_accommodation_type, student_sex } = toRefs<any>(proxy?.useDict('student_accommodation_type', 'student_sex'));

const studentList = ref<StudentVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const queryFormRef = ref<ElFormInstance>();
const studentFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const initFormData: StudentForm = {
  id: undefined,
  account: undefined,
  realName: undefined,
  facePic: undefined,
  facePicStatus: undefined,
  gender: undefined,
  classId: undefined,
  facultyId: undefined,
  dormId: undefined,
  eCardNo: undefined,
  studentNo: undefined,
  status: undefined,
  accommodationType: undefined,
  subscribeStatus: undefined,
  guardianList: []
};
const data = reactive<PageData<StudentForm, StudentQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    keyword: undefined,
    strategyGroupId: undefined,
    account: undefined,
    realName: undefined,
    facePicStatus: undefined,
    gender: undefined,
    classId: undefined,
    facultyId: undefined,
    dormId: undefined,
    eCardNo: undefined,
    studentNo: undefined,
    status: undefined,
    accommodationType: undefined,
    subscribeStatus: undefined,
    params: {}
  },
  rules: {
    account: [{ required: true, message: '平台账号不能为空', trigger: 'blur' }],
    realName: [{ required: true, message: '学生姓名不能为空', trigger: 'blur' }],
    gender: [{ required: true, message: '性别不能为空', trigger: 'change' }],
    classId: [{ required: true, message: '班级不能为空', trigger: 'change' }],
    facultyId: [{ required: true, message: '学部不能为空', trigger: 'change' }],
    dormId: [{ required: true, message: '关联宿舍不能为空', trigger: 'change' }],
    studentNo: [{ required: true, message: '学号不能为空', trigger: 'blur' }],
    status: [{ required: true, message: '学生状态不能为空', trigger: 'change' }],
    accommodationType: [{ required: true, message: '住宿类型不能为空', trigger: 'change' }],
    subscribeStatus: [{ required: true, message: '订阅状态不能为空', trigger: 'change' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询学生信息列表 */
const getList = async () => {
  loading.value = true;
  const res = await pageStudent(queryParams.value);
  studentList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  initParams();
  studentFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  loadList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加学生信息';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: StudentVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getStudent(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改学生信息';
};

/** 提交按钮 */
const submitForm = () => {
  studentFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateStudent(form.value).finally(() => (buttonLoading.value = false));
        proxy?.$modal.msgSuccess('修改成功');
      } else {
        await addStudent(form.value).finally(() => (buttonLoading.value = false));
        proxy?.$modal.msgSuccess('新增成功');
      }
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: StudentVO) => {
  const _ids = row ? [row.id] : ids.value;
  let msg = studentList.value
    .filter((e) => _ids.find((id) => e.id === id))
    .map((e) => e.realName)
    .join(',');
  await proxy?.$modal.confirm('是否确认删除学生姓名为"' + msg + '"的数据项？').finally(() => (loading.value = false));
  await delStudent(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

const initParams = () => {
  if (props.parentId === 0) {
    queryParams.value.strategyGroupId = undefined;
    queryParams.value.strategyAll = true;
  } else {
    queryParams.value.strategyAll = false;
    queryParams.value.strategyGroupId = props.groupId;
  }
};
const loadList = () => {
  initParams();
  getList();
};

defineExpose({
  loadList
});
</script>
